import { PlusOutlined } from "@ant-design/icons"
import {
  Button,
  ConfigProvider,
  Form,
  Layout,
  message,
  Spin,
  theme,
} from "antd"
import React, { useState } from "react"
import Header from "../components/Header"
import SearchBar from "../components/SearchBar"
import TaskLogDrawer from "../components/TaskLogDrawer"
import TaskModal from "../components/TaskModal"
import TaskTable from "../components/TaskTable"
import { useFirstLoading } from "../hooks/useFirstLoading"
import { useTaskLog } from "../hooks/useTaskLog"
import { useTasks } from "../hooks/useTasks"
import { useTheme } from "../hooks/useTheme"
import type { Task } from "../types/task"

const TaskManagement: React.FC = () => {
  const [query, setQuery] = useState("")
  const [modalVisible, setModalVisible] = useState(false)
  const [form] = Form.useForm()
  const [editingTask, setEditingTask] = useState<Task | null>(null)
  const [logDrawerVisible, setLogDrawerVisible] = useState(false)
  const [selectedTaskId, setSelectedTaskId] = useState<string | null>(null)

  // 主题
  const { isDarkMode, toggleTheme } = useTheme()
  // 任务相关
  const {
    tasks,
    loading,
    loadTasks,
    handleCreate,
    handleEdit,
    handleDelete,
    handleStart,
    handleStop,
    setTasks,
  } = useTasks(query)
  // 日志相关
  const { logs } = useTaskLog(selectedTaskId, logDrawerVisible)
  // 首次全局 loading
  const { firstLoading } = useFirstLoading(1500)

  // 任务创建/编辑
  const handleTaskModalOk = async (values: {
    name: string
    description?: string
    template?: string
  }) => {
    try {
      if (editingTask) {
        await handleEdit((editingTask as Task).id, {
          name: values.name,
          description: values.description ?? "",
          template: values.template ?? "",
        })
        message.success("Task updated successfully")
      } else {
        await handleCreate({
          name: values.name,
          template: values.template ?? "",
          description: values.description ?? "",
        })
        message.success("Task created successfully")
      }
    } catch (error) {
      message.error("操作失败")
    } finally {
      setModalVisible(false)
      setEditingTask(null)
    }
  }

  // 编辑任务
  const handleEditTask = (task: Task) => {
    setEditingTask(task)
    form.setFieldsValue(task)
    setModalVisible(true)
  }

  // 查看日志
  const handleViewLog = (id: string) => {
    setSelectedTaskId(id)
    setLogDrawerVisible(true)
  }

  return (
    <ConfigProvider
      theme={{
        algorithm: isDarkMode ? theme.darkAlgorithm : theme.defaultAlgorithm,
      }}
    >
      {firstLoading && <Spin fullscreen tip="加载中..." size="large" />}
      <Layout
        style={{ minHeight: "100vh", display: "flex", flexDirection: "column" }}
      >
        <Header isDarkMode={isDarkMode} toggleTheme={toggleTheme} />
        <Layout.Content
          className={`flex flex-col items-center w-full min-h-[600px] transition-colors duration-300 ${
            isDarkMode ? "bg-[#18191c]" : "bg-[#f5f6fa]"
          }`}
          style={{
            flex: 1,
            padding: "32px 0 0 0",
            maxWidth: "100vw",
            color: isDarkMode ? "#e0e0e0" : "#333",
          }}
        >
          <div className="flex w-full max-w-[700px] mb-8 items-center justify-between">
            <Button
              type="primary"
              className="new-task-btn !bg-green-500 !border-green-500 hover:!bg-green-600 hover:!border-green-600 flex items-center gap-2"
              onClick={() => {
                setEditingTask(null)
                form.resetFields()
                setModalVisible(true)
              }}
              icon={<PlusOutlined />}
            >
              新建任务
            </Button>
            <div className="flex-1 flex justify-end">
              <SearchBar
                query={query}
                setQuery={setQuery}
                onSearch={loadTasks}
              />
            </div>
          </div>
          <div className="w-full max-w-[1200px] flex-1 flex flex-col">
            <TaskTable
              tasks={tasks}
              loading={loading}
              handleStart={handleStart}
              handleStop={handleStop}
              handleEdit={handleEditTask}
              handleDelete={handleDelete}
              onViewLog={handleViewLog}
            />
          </div>
          <TaskLogDrawer
            visible={logDrawerVisible}
            onClose={() => setLogDrawerVisible(false)}
            logs={logs}
          />
          <TaskModal
            visible={modalVisible}
            onCancel={() => {
              setModalVisible(false)
              setEditingTask(null)
            }}
            onOk={handleTaskModalOk}
            form={form}
            editingTask={editingTask}
          />
        </Layout.Content>
        <Layout.Footer
          style={{
            textAlign: "center",
            background: isDarkMode ? "#1f1f1f" : "#f0f2f5",
            color: isDarkMode ? "#e0e0e0" : "#333",
            position: "sticky",
            bottom: 0,
            width: "100%",
          }}
          className="select-all"
        >
          Task Management System ©2025 Created by Fromsko
        </Layout.Footer>
      </Layout>
    </ConfigProvider>
  )
}

export default TaskManagement
